﻿//-----------------------------------------------------------------------
// <copyright file="PacketConverter.cs" company="FastNET Services">
//     Copyright (c) 2008-2009. All Rights Reserved.
// </copyright>
// <license>
//     GPLv2
// </license>
// <warranty>
//     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
//     BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//     NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
//     DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//     OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </warranty>
//-----------------------------------------------------------------------
#region Usings

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

#endregion

namespace GateShift.Common.DataPackets
{
    /// <summary>
    /// Standard class for conforming packet conversions
    /// </summary>
    public static class PacketConverter
    {
        /// <summary>
        /// Takes an IDataPacket and converts the specified instance
        /// into a Serialized byte Array to transmit through the network layer
        /// </summary>
        /// <typeparam name="T">IDataPacket based type</typeparam>
        /// <param name="packet">Instance of IDataPacket to convert to a byte array for transport</param>
        /// <returns>Byte Array containing a serialized form of the object</returns>
        public static byte[] ConvertToByteArray<T>(T packet) where T : IDataPacket
        {
            // Initialize streams
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();

            // Run the conversion
            formatter.Serialize(stream, packet);

            // Return the array
            return stream.ToArray();
        }

        /// <summary>
        /// Takes a Serialized byte Array and converts it to an instance of the specified
        /// IDataPacket based Type provided
        /// </summary>
        /// <typeparam name="T">IDataPacket based type</typeparam>
        /// <param name="data">Serialized byte Array to deserialize</param>
        /// <returns>Deserialized instance of IDataPacket</returns>
        public static T ConvertFromByteArray<T>(byte[] data) where T : IDataPacket
        {
            // Initialize streams
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream(data);

            // Return instance
            return (T)formatter.Deserialize(stream);
        }
    }
}